package com.fh.shop.api.cate.biz;

import com.alibaba.fastjson.JSON;
import com.fh.shop.api.cate.controller.CateController;
import com.fh.shop.api.cate.mapper.ICateMapper;
import com.fh.shop.api.cate.po.Cate;
import com.fh.shop.api.common.ServerResponse;
import com.fh.shop.api.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("cateService")
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class ICateServiceImpl implements ICateService {


    @Autowired
    private ICateMapper cateMapper;

    @Override
    @Transactional(readOnly = true)
    public ServerResponse findList() {
        Map res = new HashMap();
        // 每次先从缓存服务器查找
        String cateListJson = RedisUtil.get("cateList");
        if (StringUtils.isNotEmpty(cateListJson)) {
            log.debug("cateList从缓存中查找数据");
            // 将json格式字符串转为java对象[fastjson]
            List<Cate> cates = JSON.parseArray(cateListJson, Cate.class);
            // 缓存中有数据，直接返回
            return ServerResponse.success(cates);
        }
        log.debug("cateList从数据库中查找数据");
        // 缓存中没有数据，查询数据库
        List<Cate> cates = cateMapper.selectList(null);
        // java对象转json字符串 [fastjson]
        cateListJson = JSON.toJSONString(cates);
        // 往缓存中放一份
        RedisUtil.set("cateList", cateListJson);
        // 响应给前台
        return ServerResponse.success(cates);
    }
}
